using System;
using Castle.MonoRail.Framework;
using Castle.MonoRail.ActiveRecordSupport;
using DecisionesInteligentes.iEvalua.Models;
using DecisionesInteligentes.iEvalua.Web.Services;
using DecisionesInteligentes.iEvalua.Web.Filters;
using NHibernate.Expression;

namespace DecisionesInteligentes.iEvalua.Web.Controllers
{
	[Layout("users")]
	[Filter(ExecuteEnum.BeforeAction, typeof(AuthenticationFilter), ExecutionOrder=1)]
	public class UsersController : BaseController<User>
	{
		private readonly ISecurityService securityService;
		
		public UsersController(ISecurityService securityService)
		{
			this.securityService = securityService;
		}
		
		public override void Index()
		{
			List(null, new ICriterion[]
				{
					new EqExpression("ApplicationId", Application.Id)
				}
			);
		}
		
		public void ChangePassword()
		{
			if(PropertyBag["entity"] == null)
			{
				RedirectToAction("Index");
			}
		}
		
		public void ChangePassword(int id)
		{
			Load(id);
		}
		
		public void SaveChangePassword(int id, string password, string confirmpassword)
		{
			User user = User.Find(id);
			user.Password = password;
			user.ConfirmPassword = password;
			
			if(!HasValidationError(user))
			{
				try
				{
					user.Password = securityService.HashPassword(password);
					user.ConfirmPassword = user.Password;
					
					user.Update();
					
					SetPostActionEnvironment(null, "Edit", "Password has been changed",
						null, "id=" + user.Id);
						
				}catch(Exception ex)
				{
					SetPostActionEnvironment(user, "Edit", "Failed to change password due some errors.",
						new string[] { ex.Message }, null);
				}
			}else
			{
				SetPostActionEnvironment(user, "ChangePassword", "Password confirmation is not the same as password",
					GetErrorSummary(user), null);
			}
		}
		
		protected override void CreateNew(User user)
		{
			string originalPassword = user.Password;
			string originalConfirmPassword = user.ConfirmPassword;
			
			user.Application = Application;
			
			if(!HasValidationError(user))
			{
				try
				{
					user.Password = securityService.HashPassword(user.Password);
					user.ConfirmPassword = user.Password;
					
					user.Create();
					
					SetPostActionEnvironment(null, "Edit", "A new " + EntityName() + " has been created",
						null, "id=" + user.Id);
						
				}catch(Exception ex)
				{
					user.Password = originalPassword;
					user.ConfirmPassword = originalConfirmPassword;
					
					SetPostActionEnvironment(user, "New", EntityName() +  " was not saved due some errors.",
						new string[] { ex.Message }, null);
				}
			}else
			{
				SetPostActionEnvironment(user, "New", EntityName() + " has some invalid data",
					GetErrorSummary(user), null);
			}
		}
	}
}
